import Axios from "axios";
import {store} from '../store';
import {API_URL, apiList, BASE_URL} from './api'

const http = (
    url= '',
    data = {},
) => {
    let api = getApiPath(url); // 获取请求地址
    Axios.interceptors.request.use(config => {//请求拦截器
        const {userInfo} = store.getState()
        let token = userInfo.token;
        if(api.auth && !token){
            store.dispatch({type: 'userInfo', value: {}})
            // 未登录
            window.location.href = '/login'
        }
        config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        config.headers.token = token;
        return config;
    })
    Axios.interceptors.response.use(//响应拦截器
    response => {
        // console.log(response,'登录00response');
        return response
    },
    error => {
        if(error?.response?.status === 401){
            store.dispatch({type: 'userInfo', value: {}})
            // 未登录
            window.location.href = '/login'
        } 
        return error
    }    
    )
    return new Promise((resolve, reject) => {
        let mergeUrl = isUrl(api.url) ? api.url : 
        (api.url === '/index.php/api/user/savePower' || 
        api.url === '/index.php/api/user/savePowerToGroup' ||
        api.url === '/index.php/api/user/getUserPowerById' ||
        api.url === '/index.php/api/user/getGroupPower') ? (BASE_URL + api.url) : (API_URL + api.url)
        if (api.method === 'get' && JSON.stringify(data) !== '{}') {
            let query = addQueryString(data);
            mergeUrl += mergeUrl.indexOf('?') === -1 ? `?${query}` : `&${query}`
        }
        Axios({
            url: mergeUrl,
            method: api.method,
            data,
        }).then(res => {
            // console.log("响应请求成功");
            resolve(res.data)
        })
        .catch(err => {
            // console.log("return出去我再看看有什么数据");
            reject(err)
        })
    })
}

function isUrl(url) {
    return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
}

// 组装接口路径
function getApiPath(url) {
    let apiArray = url.split(".");
    let api = apiList;
    apiArray.forEach(v => {
        api = api[v];
    });
    return api;
}
// get请求-拼接参数
function addQueryString(params) {
    let paramsData = ''
    Object.keys(params).forEach(key => {
        paramsData += key + '=' + encodeURIComponent(params[key]) + '&'
    })
    return paramsData.substring(0, paramsData.length - 1)
}


export default http;